package model

import (
	"course-admin/userrpc/userrpc"

	"gorm.io/gorm"
)

type Goods struct {
	gorm.Model
	GoodsName    string  `gorm:"type:varchar(30);not null"`
	GoodsPrice   float32 `gorm:"type:decimal(10,2);not null"`
	GoodsContent string  `gorm:"type:varchar(30);not null"`
	Cid          int     `gorm:"type:int;not null"`
	UserId       int     `gorm:"type:int;not null"`
}

func (g *Goods) GoodsAdd(db *gorm.DB) error {
	return db.Debug().Create(g).Error
}

func (g *Goods) FindGoodsById(db *gorm.DB, id int64) error {
	return db.Debug().Where("id=?", id).Find(g).Error
}

func (g *Goods) GoodsShow(db *gorm.DB, in *userrpc.CommentGoodsListRequest) userrpc.CommentGoodsListResponse {
	var list userrpc.CommentGoodsListResponse
	db.Debug().Model(&Goods{}).Select("goods.*,goods.id as goods_id,users.head_img,users.nickname").
		Joins("left join users on users.id = goods.user_id").
		Where("goods.id=?", in.GoodsId).Order("goods.created_at desc").First(&list)
	return list
}

type Class struct {
	gorm.Model
	ClassName string `gorm:"type:varchar(30);not null"`
}

func (c *Class) FindCreate(db *gorm.DB, name string) error {
	return db.Debug().Where("class_name=?", name).FirstOrCreate(c).Error
}
func GoodsList(db *gorm.DB, in *userrpc.GoodsListRequest) []*userrpc.GoodsList {
	var list []*userrpc.GoodsList
	tx := db.Debug().
		Model(&Goods{}).
		Select("goods.*,users.head_img,users.nickname").
		Joins("left join users on users.id = goods.user_id").
		Scopes(Paginate(int(in.Page), int(in.Size))).
		Order("created_at desc")
	if in.GoodsName != "" {
		tx.Where("goods_name like ?", "%"+in.GoodsName+"%")
	}
	tx.Find(&list)
	return list
}

func CommentUserList(db *gorm.DB, in *userrpc.CommentGoodsListRequest) []*userrpc.CommentGoodsList {
	var list []*userrpc.CommentGoodsList
	db.Debug().Model(&Comment{}).
		Select("users.head_img,users.nickname,comments.comments as Comment").
		Joins("left join users on users.id = comments.user_id").
		Where("comments.goods_id=?", in.GoodsId).Order("comments.created_at desc").Find(&list)
	return list
}
